<!--  -->
<template>
  <div class="blank-test js-clickbody" @click="bodyClick('body')">
    <div class="chose-course-top">
      <div class="header-left">
        <span class="back-arrow" @click="quitStudy"></span>
      </div>
      <div class="course-title">
        语法填空
      </div>
      <div class="btn-group">
        <div class="spend-time">
          <img src="~assets/reverse/time.png" alt="" />
          <span>{{ spent_time | HHmmssFilter }}</span>
        </div>
        <a @click="print">打印</a>
        <a @click="lastAnswer" v-if="+detail.last_id !== 0">上次答题</a>
        <a @click="goSkill">答题技巧</a>
      </div>
    </div>
    <div class="list-wrap">
        <div class="article-content two-colum-width scrolToMinView">
          <p
            class="article-paragraph"
            v-for="(paragraph, index) in content"
            :key="`paragraph-p-${index}`"
          >
            <template v-for="(word, i) in paragraph">
              <template v-if="/###\d{0,}###/.test(word)">
                <span
                  :key="word + i"
                  class="blank"
                  @click="blankClick(word.replace(/[^0-9]/g, ''))"
                >
                  <strong
                    :data-id="word.replace(/[^0-9]/g, '')"
                    class="blank-num"
                  >{{word.replace(/[^0-9]/g, '')}}</strong>
                  <strong class="blank-val"></strong>
                </span>
              </template>
              <template v-else-if="(/([A-Za-z0-9]+['’]?[A-Za-z])/).test(word)">
                <a-popover
                  transitionName=""
                  :key="word + i"
                  overlayClassName="lookup-popover"
                  placement="bottom"
                  :visible="visibleKey === `${index}-${i}`"
                  :destroyTooltipOnHide="true"
                  trigger="click"
                >
                  <span
                    :yxp_attr="viLock?'disable':''"
                    class="pop-content-word synclock"
                    :id="`id-${index}-${i}`"
                    @click="checkWord(word,`${index}-${i}`)"
                  >
                    {{ word }}
                  </span>
                  <div slot="content">
                    <div class="lookup-content">
                      <div class="title">
                        {{ translate.prototype_word || translate.select_word }}
                        <img
                          v-show="translate.prototype_word"
                          class="icon-img"
                          @click="translateVoice"
                          src="~assets/reverse/audio-play1.png"
                          alt=""
                        />
                      </div>
                      <div class="translate">
                        {{ translate.translate || "未找到该生词" }}
                      </div>
                      <div class="btn-group">
                        <a
                          :disabled="!translate.prototype_word"
                          @click.stop="addWord"
                          ><img
                            class="icon-img"
                            src="~assets/reverse/add1.png"
                            alt=""
                          />添加生词</a
                        >
                        <a @click="translateDetail"
                          ><img
                            class="icon-img"
                            src="~assets/reverse/detail1.png"
                            alt=""
                          />单词详解</a
                        >
                      </div>
                    </div>
                  </div>
                </a-popover>
              </template>
              <template v-else>
                <span class="pop-content-word" :key="word + i">
                  {{word}}
                </span>
              </template>
            </template>
          </p>
        </div>
        <div
          v-if="+this.$route.query.num < 5"
          class="article-blank two-colum-width"
        >
          <p>答题卡</p>
          <div class="answer-wrap">
            <label
              class="answer-input"
              v-for="(input, i) in answerIdList"
              :key="`input${i}`"
            >
              <span>{{ i + 1 }}. </span>
              <input
                @blur="(e) => sbBlur(e, i)"
                @click="(e) => inputFocusHandle(e, i)"
                @input="
                  (e) => {
                    inputInputHandle(e, i, answerIdList);
                  }
                "
                maxlength="30"
                type="text"
              />
            </label>
            <!-- 占位元素 保持居中 -->
            <div class="answer-input__blank"></div>
            <div class="answer-input__blank"></div>
            <div class="answer-input__blank"></div>
            <div class="answer-input__blank"></div>
          </div>
          <div class="submit-wrap">
            <a-button
              block
              type="primary"
              ghost
              class="submit-btn"
              shape="round"
              @click="submitAnswer"
              >提交答案</a-button
            >
          </div>
        </div>
    </div>
    <Timetips ref="timetips"></Timetips>
  </div>
</template>

<script>
import {
  grammarDetailInfo,
  subGrammarDetail,
  middleStop,
  checkWord,
  addWord,
  grammarExercisePrint,
} from "@/services/reverse";
import { Popover } from "ant-design-vue";
import { SUCCESS_CODE } from "@/utils/const";
import Timetips from "@/components/Timetips";
import { mapState, mapMutations } from "vuex";
import $ from "jquery";
// fetchEndTime, validCode, proofreadSub
export default {
  name: "BlankDetail",
  components: {
    APopover: Popover,
    Timetips
  },
  data() {
    return {
      audio: null,
      viLock: false,
      lastvi: "",
      visibleKey: -1,
      visibles: {},
      BSync: {},
      detail: {},
      content: [],
      spent_time: 0,
      timer: "",
      translate: {},
      answerIdList: [],
      answer: [],
    };
  },
  computed: {
    ...mapState({
      reverseStatus: (state) => state.reverseStatus,
    }),
  },
  watch: {},
  methods: {
    ...mapMutations(["setTranslateModal", "setGrammarSkill", "setGrammarBlankAnswer"]),
    outPopClick(oi) {
      if (typeof oi == "object") {
        if (this.visibles[this.lastvi] == true) {
          let dom = document.getElementsByClassName("ant-popover-open")[0]
          dom ? dom.click() : ''
        }
      } else {
        for (let i in this.visibles) {
          if (typeof oi == "string" && oi == i) continue;
          this.visibles[i] = false;
        }
      }
    },
    bodyClick(e) {
      console.log(e, '-=-=-=-=-')
      if (e === 'body') {
        this.visibleKey = -1
      }
      if (!window[`bs:event:scroll:close`]) {
        this.visibleKey = -1
      }
    },
    fetchDetailInfo() {
      grammarDetailInfo({
        id: this.$route.query.id,
        type: this.$route.query.type,
      }).then((res) => {
        if (res.code === SUCCESS_CODE) {
          this.detail = res.data;
          let article_title = res.data.question_content;
          let string = article_title.split(/\n/);
          this.content = string.map((v) => {
            return v.split(" ");
          });
          this.$nextTick(() => {
            $(".blank-num").each((i) => {
              this.answerIdList.push({
                id: $(this).data("id"),
                position: i,
                type: 1,
                right_answer: "",
              });
            });
          })
        }
      });
    },
    checkWord(value, i) {
      // this.outPopClick(i);
      // this.lastvi = i;
      if (!value || this.viLock) return;
      this.viLock = true;
      checkWord({ word: value }).then((res) => {
          this.translate = res.data;
          this.visibleKey = i
          // this.visibles[i] = !this.visibles[i];
          this.viLock = false;
      });
    },
    addWord() {
      addWord({
        prototype_word: this.translate.prototype_word,
        select_word: this.translate.select_word,
        question_type: 3,
        is_diff: "0",
      }).then((res) => {
        if (res.code === SUCCESS_CODE) {
          this.$message.success("添加生词成功");
        }
      });
    },
    translateVoice() {
      this.audio.src = this.translate.project_voice;
      this.audio.play();
    },
    translateDetail() {
      this.setTranslateModal({
        visible: true,
        word: this.translate.select_word,
      });
      document.getElementById("app").click();
    },
    sbBlur(e, i) {
      // 补发失去焦点数据
      // this.BSync &&
      //   this.BSync.socket.emit("input:text", {
      //     index: i,
      //     tagName: "INPUT",
      //     value: e.target.value,
      //   });
    },
    inputFocusHandle(e, i) {
      $(e.target)
        .parent("label")
        .addClass('active')
        .siblings()
        .removeClass('active')
      let blankList = $(".article-content .blank");
      blankList.attr("style", "");
      blankList.eq(i).css({
        "background-color": "#FF9D00",
        color: "#fff",
        border: "none",
      });
    },
    inputInputHandle(e, i, answerIdList) {
      let val = e
        ? e.target.value
        : document.getElementsByTagName("input")[i].value;
      let result = val.replace(/[^A-Za-z0-9'’ ]/g, "");
      answerIdList[i]['right_answer'] = result
      $(e.srcElement).val(result)
      let blank = $(".article-content .blank-val").eq(i);
      blank.html(result ? "." + result : "");
    },
    lastAnswer() {
      this.setGrammarBlankAnswer({
        visible: true,
        id: this.detail.last_id,
        type: 1
      })
    },
    goSkill() {
      this.setGrammarSkill({
        visible: true,
        type: "1",
        chapter_id: this.reverseStatus.chapters_id,
        curr_id: this.reverseStatus.curr_id,
      });
    },
    quitStudy() {
      this.$yxpConfirm({
        msg: "是否退出答题",
      })
        .then(() => {
          middleStop({
            question_type: 3,
            id: this.reverseStatus.chapters_id,
          });
          console.log(this);
          this.$router.go(-1);
        })
        .catch(() => {});
    },
    blankClick(id) {
      let blankList = $(".article-content .blank");
      blankList.attr("style", "");
      blankList.eq(+id - 1).css({
        "background-color": "#FF9D00",
        color: "#fff",
        border: "none",
      });

      $(".answer-input")
      .siblings()
      .removeClass('active')
      $(".answer-input")
        .eq(+id - 1)
        .addClass('active')
        .find("input")
        .focus();
    },
    subBlankAnswer(answer) {
      subGrammarDetail({
        id: this.$route.query.id,
        type: "1",
        user_answer: JSON.stringify(answer),
      }).then((res) => {
        if (res.code === SUCCESS_CODE) {
          let last_id = res.data;
          this.$message.success("提交成功");
          this.$router.push({
            path: "/reverse/grammar-blankanswer",
            query: {
              id: last_id,
              isSub: true,
              type: this.$route.query.type,
            },
          });
        }
      });
    },
    print() {
      grammarExercisePrint({
        type: 4,
        id: this.detail.id,
      }).then((res) => {
        if (res.code === SUCCESS_CODE) {
          this.$message.success("已提交打印,请到管理平台进行打印");
        } else {
          this.$message.error("您打印的过于频繁，请休息一下");
        }
      });
    },
    submitAnswer() {
      let answerList = this.answerIdList.filter((v) => v.right_answer);
      this.answerIdList = this.answerIdList.map((v) => {
        v.right_answer &&
          (v.right_answer = v.right_answer.trim().replace(/\s+/g, " "));
        return v;
      });
      if (!answerList.length) {
        this.$yxpConfirm({
          msg: "您还没有答题，是否提交",
        })
          .then(() => {
            this.subBlankAnswer(this.answerIdList);
          })
          .catch(() => {});
      } else {
        this.subBlankAnswer(this.answerIdList);
      }
    },
    scrollRmPop() {
        if (!window[`bs:event:scroll:close`]) {
            $(".ant-popover").hide();
            $('.ant-popover-open').removeClass('ant-popover-open')
        }
    },
  },
  created() {
    let that = this;
    this.fetchDetailInfo();
    // this.BSync = window.isBSync();
    // this.BSync &&
    //   this.BSync.socket.on("input:text", (data) => {
    //     document.getElementsByTagName("input")[data.index].value = data.value;
    //     that.inputInputHandle("", data.index, that.answerIdList);
    //   });
    // document.body.addEventListener("click", this.outPopClick);
    document.addEventListener('scroll', this.bodyClick, true)
  },

  mounted() {
    this.timer = setInterval(() => {
      this.spent_time++;
    }, 1000);
    this.audio = document.getElementById("reverse-audio");
  },
  beforeDestroy() {
    clearInterval(this.timer);
    // document.body.removeEventListener("click", this.outPopClick);
    document.removeEventListener('scroll', this.bodyClick, true)
    if (this.audio !== null) {
      this.audio.pause()
    }
    this.$refs.timetips.stopTimer();
    this.$refs.timetips.stopEndTimer();
  },
};
</script>
<style lang="less" scoped>
/* @import url(); 引入公共css类 */
@import url("./test.less");
</style>
